function canReattributeEvent(eventToReattribute, newAgendaId, successExec, failedExec) {
    var currentAuthorizedPrestations = window.calendarCache['AgendaPrestations'][newAgendaId];
    if (in_array(eventToReattribute.prestation_id, currentAuthorizedPrestations)) {
        successExec();
    } else {
        failedExec();
    }
}

function initLocalStorage() {
    // TODO : NO EVENT CREATION BEFORE LOCAL STORAGE HAS DONE ITS WORK
    $.jStorage.set('SAVE_EVENT', null);
    $.jStorage.set('DELETE_EVENT', null);
    $.jStorage.set('MOVE_EVENT', null);
    $.jStorage.set('RESIZE_SLOT', null);
    $.jStorage.set('CREATE_CLIENT', null);
    $.jStorage.set('SAVE_NOTE', null);
    $('#container #menu a, #labels a').click(function() {
        followLink = $(this).attr('href');
        if ($.jStorage.get('SAVE_EVENT') != null ||
                $.jStorage.get('DELETE_EVENT') != null ||
                $.jStorage.get('MOVE_EVENT') != null ||
                $.jStorage.get('RESIZE_SLOT') != null ||
                $.jStorage.get('CREATE_CLIENT') != null ||
                $.jStorage.get('SAVE_NOTE') != null) {
            $('#EXIT_dialog').html('Etes vous sur de vouloir quitter le calendrier ? Toutes les données ne sont pas sauvegardées');
            alert_jqueryui_($('#EXIT_dialog'), 'Sauvegarder et quitter', 'Quitter sans sauvegarder', 'Annuler', function() {
                $('#EXIT_dialog').hide();
                executeLocalStack(function() {
                    location.href = followLink;
                });
            }, function() {
                location.href = followLink;
            });
            return false;
        }
    });
}

function addToLocalStore(stackName, calEvent) {
    window.localRefresh = true;
    var stackItem = $.jStorage.get(stackName);
    $('#sync-reload-action').fadeIn();
    if (stackItem === null) {
        stackItem = new Array();
    }
    stackItem.push(calEvent);
    $.jStorage.set(stackName, stackItem);
    $('#sync-data .reload').show();
    if (stackName == 'SAVE_EVENT') {
        add_replace_event(calEvent);
    } else if (stackName == 'DELETE_EVENT') {
        remove_event(calEvent);
    } else if (stackName == 'MOVE_EVENT') {
        move_event(calEvent);
    } else if (stackName == 'RESIZE_SLOT') {
        resize_slot(calEvent);
    } else if (stackName == 'CREATE_CLIENT') {
        // Nothing is requiered
    } else if (stackName == 'SAVE_NOTE') {

    }
    setTimeout(function() {
        $('#calendar').weekCalendar('refresh');
    }, 500);
}





function executeLocalStack(postExec) {
    if (!$('#FORMCONTAINER_localitem').is(':visible') && !$('#EXIT_dialog').is(':visible')) {
        if ($('.tipsy-s').length) {
            $('.tipsy-s').remove();
        }
        clearInterval(window.calendarCache['timer']);
        if (window.calendarCache['is_syncing'] !== true) {
            preventAction();
            window.calendarCache['is_syncing'] = true;
            $('#sync-reload-action').hide();
            ajaxSuccessFail(WEBROOT + '/FastService/Online.php', new Array(), function(data) {
                $('#sync-data .infos').html('<font color="orange">Synchronisation en cours</font><br/>').show();
                $('.offline').hide();
                localCreateClient(function() {
                    $('.localCreateClient').css('background', 'green');
                    localSaveEvent(function() {
                        $('.localSaveEvent').css('background', 'green');
                        localMoveEvent(function() {
                            $('.localMoveEvent').css('background', 'green');
                            localResizeEvent(function() {
                                $('.localResizeEvent').css('background', 'green');
                                localDeleteEvent(function() {
                                    $('.localDeleteEvent').css('background', 'green');
                                    localSaveNote(function() {
                                        $('.localSaveNote').css('background', 'green');
                                        //resynchronizeAgendas(function() {
                                        $('.resynchronizeAgendas').css('background', 'green');
                                        allowAction();
                                        window.calendarCache['is_syncing'] = false;
                                        if (postExec != undefined) {
                                            postExec();
                                        }
                                        /*setTimeout(function() {
                                         $('.load-cells div').css('background', 'white');
                                         $('.reload').hide();
                                         }, 500);*/
                                        $('.load-cells div').css('background', 'white');
                                        $('.reload').hide();
                                        $('#calendar').weekCalendar('refresh');
                                        $('#sync-data .infos').html('Agendas synchronisés<br/>').delay(2000).fadeOut();
                                        window.calendarCache['timer'] = window.setInterval(function() {
                                            executeLocalStack();
                                        }, window.calendarCache['sync_interval']);
                                        //});
                                    });
                                });

                            });
                        });
                    });
                });
            },
                    function() {
                        $('#sync-data .infos').html('<font color="orange">Impossible de synchroniser</font><br/>').show();
                        $('#sync-reload-action').show();
                        $('.offline').show();
                        allowAction();
                        window.calendarCache['is_syncing'] = false;
                        window.calendarCache['timer'] = window.setInterval(function() {
                            executeLocalStack();
                        }, window.calendarCache['sync_interval']);
                        if (postExec != undefined) {
                            postExec();
                        }
                    });
        }
    }
}

// $('#calendar').weekCalendar('refresh');
function sendConfirmation(newCalEvent) {
    post_array = new Array();
    $("#message").dialog({
        width: 300,
        modal: true,
        buttons: {
            "Modification pour des raisons internes (prévient le client par mail et/ou SMS)": function() {
                $('#message').dialog('close');
                var post_array = {};
                post_array['event_id'] = newCalEvent.id;
                post_array['function'] = 'internal';
                ajaxForce("WEBROOT/getdata/templated_mail", post_array, function(data) {
                    if (getRest(data)['code'] == 200) {
                        notification_jqueryui(getRest(data)['message']);
                    }
                });
            },
            "Modifié à la demande du client": function() {
                $('#message').dialog('close');
                var post_array = {};
                post_array['event_id'] = newCalEvent.id;
                post_array['function'] = 'client';
                ajaxForce("WEBROOT/getdata/templated_mail", post_array, function(data) {
                    if (getRest(data)['code'] == 200) {
                        notification_jqueryui(getRest(data)['message']);
                    }
                });
            },
            "Ne pas envoyer de notification": function() {
                $('#message').dialog('close');
            }
        }
    });
}



function fillComboPresta(calEvent) {
    if (calEvent.agenda_id != undefined) {
        currentAgendaId = calEvent.agenda_id;
    } else {
        currentAgendaId = parseInt(window.agendaIdArray[calEvent.userId]);
    }
    var currentAuthorizedPrestations = window.calendarCache['AgendaPrestations'][currentAgendaId];
    var allData = window.calendarCache['ComboPresta'];
    var res = '';
    var fieldData = jQuery.extend({}, allData[0]['children']);
    // Filter by authorized prestations
    for (var _optionKey in fieldData) {
        var _optionValue = fieldData[_optionKey];
        if (_optionValue != undefined && _optionValue != null && is_array(_optionValue['children'])) {
            for (var _optionKey2 in _optionValue['children']) {
                var _optionValue2 = _optionValue['children'][_optionKey2];
                if (_optionValue2 != undefined && !in_array(_optionValue2['key'], currentAuthorizedPrestations)) {
                    delete fieldData[_optionKey]['children'][_optionKey2];
                }
            }
        } else {
            if (_optionValue != undefined && _optionValue != null && !in_array(_optionValue['key'], currentAuthorizedPrestations)) {
                delete fieldData[_optionKey];
            }
        }
    }
    var bDisplayAtLeastOneItem = false;
    for (var optionKey in fieldData) {
        var optionValue = fieldData[optionKey];
        if (optionValue != undefined && optionValue != null && is_array(optionValue['children'])) {
            res += '<optgroup label="' + optionValue['title'] + '">';
            for (var optionKey2 in optionValue['children']) {
                var optionValue2 = optionValue['children'][optionKey2];
                if (optionValue2 != null) {
                    var selected_flag = (calEvent.prestation_id == optionValue2['key']) ? ' selected ' : '';
                    res += '<option ' + selected_flag + ' value="' + optionValue2['key'] + '">' + optionValue2['title'] + '</option>';
                    bDisplayAtLeastOneItem = true;
                }
            }
            res += '</optgroup>';
        } else {
            if (optionValue != null) {
                selected_flag = (calEvent.prestation_id == optionValue['key']) ? ' selected ' : '';
                res += '<option ' + selected_flag + ' value="' + optionValue['key'] + '">' + optionValue['title'] + '</option>';
                bDisplayAtLeastOneItem = true;
            }
        }
    }
    if (!bDisplayAtLeastOneItem) {
        var extraSaveInfos = "<div class='extra-save-infos'>Veuillez assigner au moins une prestation à cet agenda</div>";
        $('.erra-form-jqueryui-submit_button[name="saveActionLocalStorage"]').after(extraSaveInfos);
        $('.erra-form-jqueryui-submit_button[name="saveActionLocalStorage"]').hide();
    }
    $('#localitem_prestation_id').html(res);
    $('#localitem_prestation_id').trigger("liszt:updated");
}
